<?php
declare(strict_types=1);

namespace ExpressionEngine\VariableEngine;

use Contract\Exceptions\LogicException;
use Contract\Exceptions\ValidationException;

class VariableEngine implements VariableEngineInterface
{
    protected VariableLexical $variableLexical;
    protected VariableCompile $variableCompile;

    public function __construct(VariableLexical $variableLexical, VariableCompile $variableCompile)
    {
        $this->variableLexical = $variableLexical;
        $this->variableCompile = $variableCompile;
    }

    public function is(string $variable): bool
    {
        return preg_match('/^{.+}$/', $variable) > 0;
    }

    public function get(string $variable): string
    {
        return substr($variable, 1, strlen($variable) - 2);
    }

    /**
     * @param string $variable
     * @param array $context
     * @param array $variableCompileList
     * @return mixed
     * @throws LogicException
     * @throws ValidationException
     */
    public function compile(string $variable, array $context, array $variableCompileList): mixed
    {
        $variableTree = $this->variableLexical->parse($variable);
        return $this->variableCompile->exec($variableTree, $context, $variableCompileList);
    }


    /**
     * @param array $variableList
     * @param array $context
     * @return mixed
     * @throws LogicException
     * @throws ValidationException
     */
    public function compileList(array $variableList, array $context): array
    {
        $variableCompileList = [];
        foreach ($variableList as $key => $variable) {
            $variableCompileList[$key] = $this->compile($variable, $context, $variableCompileList);
        }
        return $variableCompileList;
    }
}